﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml;
using System.ServiceModel.Syndication;
using System.Windows.Threading;
using System.Diagnostics;

namespace Knowledgecast.Twitter.WPF.App
{
    /// <summary>
    /// Interaction logic for SearchTimeline.xaml
    /// </summary>
    public partial class SearchTimeline : UserControl, ITimelinePanel
    {
        DispatcherTimer timer;

        public SearchTimeline()
        {
            InitializeComponent();
            timer = new DispatcherTimer();
            timer.Tick += new EventHandler(timer_Tick);
            timer.Interval = new TimeSpan(0, 5, 0);
        }

        void timer_Tick(object sender, EventArgs e)
        {
            Load();
        }

        public string Query { get; set; }
        public TwitterApi Twitter { get; set; }
        public string PanelTitle { get; set; }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            txtTitle.Text = PanelTitle;
            timer.Start();
            Load();
        }

        void Load()
        {
            try
            {
                Dispatcher.BeginInvoke(new Action(() => itmsSearchTimeline.ItemsSource = Twitter.GetSearchResults(Query)), null);
            }
            catch (Exception ex)
            {
                Debug("Load crashed: " + ex.Message + ": " + ex.StackTrace);
            }
        }

        private void btnClose_Click(object sender, RoutedEventArgs e)
        {
            if (CloseRequested != null)
            {
                CloseRequested(this);
            }
        }

        void Debug(string message)
        {
            string debugMessage = "[" + DateTime.Now.ToShortDateString() + DateTime.Now.ToShortTimeString() + "] - " + PanelTitle;
            debugMessage += ": " + message;
            Trace.WriteLine(debugMessage);
        }

        #region ITimelinePanel Members

        public event CloseRequestedDelegate CloseRequested;

        #endregion
    }
}
